#include "socket.hpp"
#include <signal.h>
#include <functional>
#include <string>
#include <signal.h>
//                              函数的返回值    函数的参数
using func_t = std::function<std::string(std::string &package)>;
// using 类型名 function<返回值(参数)>

int i = 0;

class Tcpserver
{
public:
    Tcpserver(uint16_t port, func_t callback)
        : port_(port), callback_(callback)
    {
    }

    ~Tcpserver()
    {
    }

public:
    void Init()
    {
        listensock_.Socket();
        listensock_.Bind(port_);
        listensock_.Listen();
    }
    void Start()
    {
        signal(SIGCHLD, SIG_IGN);
        signal(SIGPIPE, SIG_IGN);
        while (true)
        {
            std::string clientip;
            uint16_t clientport;
            int sockfd = listensock_.Accept(&clientip, &clientport);

            if (fork() == 0)
            {
                // 子进程删除套接字文件描述符,只需要accept获得sock文件即可
                listensock_.Close();
                // 用来存储一大批报文
                std::string inbuffer_stream;
                while (true)
                {
                    char buffer[1024];
                    ssize_t n = read(sockfd, buffer, sizeof(buffer));
                    if (n > 0)
                    {
                        buffer[n] = 0;
                        inbuffer_stream += buffer;
                        while (true)
                        {
                            std::string info;
                            // callback函数返回一个string,参数是一个string
                            // 按理来说该处应该是一个输出型参数,但是代码案例设计有些出入(会改变inbuffer_stream的内容)
                            info = callback_(inbuffer_stream);
                            // 必须要有一个完整的报文才进行操作, info如果为空就说明报文有问题
                            if (info.empty())
                                break;

                            lg(Debug, "debug, response:\n%s", info.c_str());
                            lg(Debug, "debug:\n%s", inbuffer_stream.c_str());

                            write(sockfd, info.c_str(), info.size());
                        }
                    }
                    else
                        break;
                }
                exit(0);
            }
            // 父进程
            close(sockfd);
        }
    }

private:
    Sock listensock_;
    uint16_t port_;
    func_t callback_;
};